package com.canyou.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.canyou.constants.CommonConstants;
import com.canyou.system.entity.perm.PermissionTreeVO;
import com.canyou.system.mapper.MenuMapper;
import com.canyou.system.mapper.RoleMenuMapper;
import com.canyou.system.model.RoleMenu;
import com.canyou.system.service.RoleMenuService;
import com.canyou.utils.TreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author canyou
 * @since 2019-05-31
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<PermissionTreeVO> getRoleMenuByRoleId(Long roleId) {
        // 获取有权限的菜单
        List<Long> menuIds = baseMapper.getMenuIdByRoleId(roleId);
        // 获取所有菜单
        List<PermissionTreeVO> menuList = menuMapper.getAllMenuList();
        // 选中有权限的菜单
        checkedMenu(menuList, menuIds);
        List<PermissionTreeVO> menuTree = TreeUtils.build(menuList, CommonConstants.DEFAULT_PARENT_ID);
        return menuTree;
    }

    /**
     * 选中菜单
     *
     * @param menuList 所有菜单
     * @param menuIds  有权限的菜单
     */
    private void checkedMenu(List<PermissionTreeVO> menuList, List<Long> menuIds) {
        menuList.forEach(menu -> {
            if (menuIds.stream().anyMatch(ckmId -> ckmId.equals(menu.getId()))) {
                menu.setChecked(true);
            }
        });
    }

}
